import { useEffect, useMemo, useState } from 'react';
import {
  Button,
  Popconfirm,
  Space,
  Table,
  Typography,
  Notification,
} from '@douyinfe/semi-ui';
import {
  IconAlertTriangle,
  IconDeleteStroked,
  IconEditStroked,
} from '@douyinfe/semi-icons';
import { ColumnProps } from '@douyinfe/semi-ui/lib/es/table';
import { PaginationProps } from '@douyinfe/semi-ui/lib/es/pagination';
import { usePageContext, useStoreContext } from '../integral-context';
import TablePagination, {
  onPageParamsChange,
} from '@/widgets/table-pagination';
import { pageSizeOpts } from '../integral-helper';
import BaseColumns from './integral-columns';
import { fetchItems } from '../reducer/integral-actions';
import { deleteItem } from '../reducer/integral-api';

const IntegralTable = () => {
  const { Text } = Typography;

  const PageContext = usePageContext();
  const {
    state: { integral },
    useDispatch,
  } = useStoreContext();
  const PageAction = useMemo(() => {
    return {
      queryParams: PageContext.queryParams,
      setQueryParams: PageContext.setQueryParams,
      addRecord: PageContext.addRecord,
      editRecord: PageContext.editRecord,
      delRecord: PageContext.delRecord,
      detailRecord: PageContext.detailRecord,
    };
  }, [PageContext]);

  const { entities, totalCount, key } = integral;

  const columns: ColumnProps[] = [
    {
      title: '序号',
      dataIndex: 'id',
      // sorterKey: 'id',
      // sorter: true,
      width: 100,
      fixed: true,
      align: 'center',
      render: (_, __, index) => (
        <>
          {(PageAction.queryParams.pageNum - 1) *
            PageAction.queryParams.pageSize +
            index +
            1}
        </>
      ),
    },
    ...BaseColumns,
    {
      title: '操作',
      width: 300,
      dataIndex: 'action',
      render: (text, record, index) => {
        return (
          <Space>
            <Button
              icon={<IconEditStroked />}
              onClick={() => {
                PageAction.editRecord(record[key]);
              }}
            ></Button>
          </Space>
        );
      },
    },
  ];

  const onRowEvent: any = useMemo(
    () => (record: any, index: number) => {
      return {
        className: 'group/item',
      };
    },
    []
  );

  const paginationOptions = useMemo(
    () => ({
      total: totalCount,
      queryParams: PageAction.queryParams,
      pageSizeOpts,
    }),
    [PageAction, integral]
  );

  return (
    <TablePagination paginationOpts={paginationOptions}>
      {(paginationOpts: PaginationProps) => (
        <Table
          size='small'
          columns={columns}
          dataSource={entities}
          onChange={(params: any) =>
            onPageParamsChange(params, PageAction.setQueryParams)
          }
          pagination={paginationOpts}
          onRow={onRowEvent}
          bordered={false}
        />
      )}
    </TablePagination>
  );
};

export default IntegralTable;
